﻿var g_eventOverlapped = false; //IMPORTANT
var eventType = "BookEvents"; //or "WaitingList"


var g_strControlIDs = new Array();

var isMeetingRoomComplex = false;
var isCheckingDuplicateError = false;

var lastStartDate = '',
    lastEndDate = '';

var last_weekly_weekFrequency = "",
    last_monthly_day = "",
    last_monthly_monthFrequency,
    last_monthlyByDay_monthFrequency;

var lastUserName = '';

var currentEventId = null;
var usedResourceIDs = [];

var checkedEvent = { "webUrl": null,
    "listName": null,
    "startDate": null,
    "startHour": null,
    "startMinutes": null,
    "endDate": null,
    "endHour": null,
    "endMinutes": null,
    "bookingRoom": null,
    "currentEventId": null,
    "isRecurred": null,
    "rFrequency": null,
    "rInterval": null,
    "rOptions": null
};

function PreSaveAction() {
    // This is in case user presses save button right after selecting date and time
    if (g_eventOverlapped == true) {
        if (isCheckingDuplicateError)
            alert("There's an error when checking events!\nPlease try again.");
        else {
            var content = "";

            if (eventType == "BookEvents") {
                content = $(".bookingstatus-info").html().replace(/<br\s*\/?>/mgi, "\n").replace(/<\/?b\s*\/?>/mgi, "");
            }
            else if (eventType == "WaitingList") {
                content = $(".waitstatus-info").html().replace(/<br\s*\/?>/mgi, "\n").replace(/<\/?b\s*\/?>/mgi, "");
            }

            if ($.trim(content) == "") {
                content = "System is processing. Please wait...";
            }
            alert(content);
        }
    }

    return !g_eventOverlapped;

}

// This function is called from OnLoad of the form, it binds event handler to the date and time controls
function FindOverlappedEvents(listName) {

    currentEventId = $().SPServices.SPGetQueryString().ID ? $().SPServices.SPGetQueryString().ID.split(".")[0] : null;

    $("#" + g_strControlIDs["SPBookingRoom"] +
//      ",#" + g_strControlIDs["SPEventDate"] +
      ",#" + g_strControlIDs["SPEventDate"] + "Hours" +
      ",#" + g_strControlIDs["SPEventDate"] + "Minutes" +
//      ",#" + g_strControlIDs["SPEndDate"] +
      ",#" + g_strControlIDs["SPEndDate"] + "Hours" +
      ",#" + g_strControlIDs["SPEndDate"] + "Minutes").on('change', function (e) {
          validateDates(listName);
      });


    var intervalDateChange;
    if ($("input[id$=RecurrenceField]").prop("checked") == false) {
        //not check Reccurence, then set interval
        intervalDateChange = setInterval(function () {
            if ($("#" + g_strControlIDs["SPEventDate"]).val() != lastStartDate) {
                lastStartDate = $("#" + g_strControlIDs["SPEventDate"]).val();
                validateDates(listName);
            }

            if ($("#" + g_strControlIDs["SPEndDate"]).val() != lastEndDate) {
                lastEndDate = $("#" + g_strControlIDs["SPEndDate"]).val();
                validateDates(listName);
            }
        }, 1000);
    }
    else {
        //if checked Recurrence, then hide some conditions
        if ($("input[id$=recurrencePatternType2]").prop("checked") == true) {
            $("input[id$=recurrencePatternType3]").click(); //set weekly
        }
        $("input[id$=recurrencePatternType2]").parent().hide(); //hide daily
        $("input[id$=recurrencePatternType5]").parent().hide(); //hide yearly

        if ($("input[id$=endDateRangeType0]").prop("checked") == true || $("input[id$=endDateRangeType1]").prop("checked") == true) {
            $("input[id$=endDateRangeType2]").click(); //set End by

            //set value End by if empty
            if ($.trim($("input[id$='windowEnd_windowEndDate']").val()) == "")
            {
                $("input[id$='windowEnd_windowEndDate']").val($("input[id$='windowStart_windowStartDate']").val());
            }
        }
        $("input[id$=endDateRangeType0]").parents("tr:first").hide(); // hide No end date
        $("input[id$=endDateRangeType1]").parents("tr:first").hide(); // hide End after

        //$("select[id$=monthlyByDay_day]").find("option[value=weekday]").remove().end().find("option[value=weekend_day]").remove();

        //bind event handler
        $("td.ms-formlabel:contains('Start Time')").next().find("select").on('change', function (e) {
            validateDates(listName);
        });
        $("td.ms-formlabel:contains('End Time')").next().find("select").on('change', function (e) {
            validateDates(listName);
        });

        $("input:radio, input:checkbox, select", ".ms-formrecurrence").on('change', function (e) {
            validateDates(listName);
        });

        intervalDateChange = setInterval(function () {
            if ($("input[id$='windowStart_windowStartDate']").val() != lastStartDate) {
                lastStartDate = $("input[id$='windowStart_windowStartDate']").val();
                validateDates(listName);
            }

            if ($("input[id$='windowEnd_windowEndDate']").val() != lastEndDate) {
                lastEndDate = $("input[id$='windowEnd_windowEndDate']").val();
                validateDates(listName);
            }

            if ($("input[id$='weekly_weekFrequency']").val() != last_weekly_weekFrequency) {
                last_weekly_weekFrequency = $("input[id$='weekly_weekFrequency']").val();
                validateDates(listName);
            }

            if ($("input[id$='monthly_day']").val() != last_monthly_day) {
                last_monthly_day = $("input[id$='monthly_day']").val();
                validateDates(listName);
            }

            if ($("input[id$='monthly_monthFrequency']").val() != last_monthly_monthFrequency) {
                last_monthly_monthFrequency = $("input[id$='monthly_monthFrequency']").val();
                validateDates(listName);
            }

            if ($("input[id$='monthlyByDay_monthFrequency']").val() != last_monthlyByDay_monthFrequency) {
                last_monthlyByDay_monthFrequency = $("input[id$='monthlyByDay_monthFrequency']").val();
                validateDates(listName);
            }
        }, 1000);
    }

}

var statusId = '';
var notifyId = '';

function AddNotification() {
    notifyId = SP.UI.Notify.addNotification("System is validating your booking. Please wait...", true);
}

function RemoveNotification() {
    SP.UI.Notify.removeNotification(notifyId);
    notifyId = '';
}

// This gets called every time onblur is fired on controls
function validateDates(listName) {
    g_eventOverlapped = true; //temporary while the ajax is calling. To prevent user press Save button while checking

    //setTimeout is used for delaying in case of changing the Start Time, system will change the End Time automatically and event handler is not fired
    setTimeout(function () {
        var bookingRoom = $("#" + g_strControlIDs["SPBookingRoom"]).find("option:selected").val(),
        startDate = $("#" + g_strControlIDs["SPEventDate"]).val(),
        startHour = $("#" + g_strControlIDs["SPEventDate"] + "Hours").find("option:selected").val(),
        startMinutes = $("#" + g_strControlIDs["SPEventDate"] + "Minutes").find("option:selected").val(),
        endDate = $("#" + g_strControlIDs["SPEndDate"]).val(),
        endHour = $("#" + g_strControlIDs["SPEndDate"] + "Hours").find("option:selected").val(),
        endMinutes = $("#" + g_strControlIDs["SPEndDate"] + "Minutes").find("option:selected").val();

        var isRecurred = "",
            rFrequency = "",
            rInterval = "",
            rOptions = "";

        if ($("input[id$=RecurrenceField]").prop("checked") == true) {
            isRecurred = "1";

            startDate = $("input[id$='windowStart_windowStartDate']").val();
            endDate = $("input[id$='windowEnd_windowEndDate']").val()

            var $StartTimeContainer = $("td.ms-formlabel:contains('Start Time')").next();
            startHour = $StartTimeContainer.find("select[id$=DateTimeFieldDateHours] option:selected").val();
            startMinutes = $StartTimeContainer.find("select[id$=DateTimeFieldDateMinutes] option:selected").val();

            var $EndTimeContainer = $("td.ms-formlabel:contains('End Time')").next();
            endHour = $EndTimeContainer.find("select[id$=DateTimeFieldDateHours] option:selected").val();
            endMinutes = $EndTimeContainer.find("select[id$=DateTimeFieldDateMinutes] option:selected").val();

            if ($("input[id$=recurrencePatternType3]").prop("checked") == true) {
                rFrequency = "Weekly";

                rInterval = $("input[id$=weekly_weekFrequency]").val();

                if ($("input[id$=weekly_multiDays_0]").prop("checked") == true) rOptions += "0" + ",";
                if ($("input[id$=weekly_multiDays_1]").prop("checked") == true) rOptions += "1" + ",";
                if ($("input[id$=weekly_multiDays_2]").prop("checked") == true) rOptions += "2" + ",";
                if ($("input[id$=weekly_multiDays_3]").prop("checked") == true) rOptions += "3" + ",";
                if ($("input[id$=weekly_multiDays_4]").prop("checked") == true) rOptions += "4" + ",";
                if ($("input[id$=weekly_multiDays_5]").prop("checked") == true) rOptions += "5" + ",";
                if ($("input[id$=weekly_multiDays_6]").prop("checked") == true) rOptions += "6" + ",";

                if (rOptions != "") rOptions = rOptions.substring(0, rOptions.length - 1);
            }
            else if ($("input[id$=recurrencePatternType4]").prop("checked") == true) {
                rFrequency = "Monthly";

                if ($("input[id$=monthlyRecurType0]").prop("checked") == true) {
                    //row 1

                    rInterval = $("input[id$=monthly_monthFrequency]").val();

                    rOptions = $("input[id$=monthly_day]").val();
                }
                else {
                    //row 2

                    rInterval = $("input[id$=monthlyByDay_monthFrequency]").val();

                    rOptions = $("select[id$=monthlyByDay_weekOfMonth]")[0].selectedIndex + "," + $("select[id$=monthlyByDay_day]")[0].selectedIndex;
                }
            }
        }

        //console.log not work on IE8 and older
        //        console.log("listName = " + listName);
        //        console.log("startDateCtl.value = " + startDate);
        //        console.log("startHour = " + startHour);
        //        console.log("startMinutes = " + startMinutes);
        //        console.log("endDateCtl.value = " + endDate);
        //        console.log("endHour = " + endHour);
        //        console.log("endMinutes = " + endMinutes);
        //        console.log("bookingRoom = " + bookingRoom);
        //        console.log("currentEventId = " + $().SPServices.SPGetQueryString().ID);
        //        console.log("===============================================================");

        if (checkedEvent.startDate != startDate || checkedEvent.startHour != startHour || checkedEvent.startMinutes != startMinutes
        || checkedEvent.endDate != endDate || checkedEvent.endHour != endHour || checkedEvent.endMinutes != endMinutes
        || checkedEvent.bookingRoom != bookingRoom || checkedEvent.isRecurred != isRecurred || checkedEvent.rFrequency != rFrequency
        || checkedEvent.rInterval != rInterval || checkedEvent.rOptions != rOptions) {

            //            console.log("called GetCalendarOverlap *******************");
            //            console.log("===============================================================");

            var url = $().SPServices.SPGetCurrentSite() + '/_vti_bin/RBSService.svc/GetCalendarOverlap';
            AddNotification();
            $.ajax({
                url: url,
                dataType: "json",
                type: "GET",
                cache: false,
                data: { "webUrl": $().SPServices.SPGetCurrentSite(),
                    "listName": listName,
                    "startDate": startDate,
                    "startHour": startHour,
                    "startMinutes": startMinutes,
                    "endDate": endDate,
                    "endHour": endHour,
                    "endMinutes": endMinutes,
                    "bookingRoom": bookingRoom,
                    "currentEventId": "0",
                    "isRecurred": isRecurred,
                    "rFrequency": rFrequency,
                    "rInterval": rInterval,
                    "rOptions": rOptions,
                    "isAdmin": hasFullControlPermission ? "1":"0"
                },
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    //g_eventOverlapped = false; //release temporary status while checking // will release in validateWaitingList
                    //RemoveNotification();// will release in validateWaitingList

                    OnCallComplete(data.GetCalendarOverlapResult.Message);

                    if (data.GetCalendarOverlapResult.UsedResourceIDs) {
                        usedResourceIDs = data.GetCalendarOverlapResult.UsedResourceIDs.split(",");
                    }
                    else {
                        usedResourceIDs = [];
                    }

                    BlockResourceRequest();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //g_eventOverlapped = false; //release temporary status while checking // will release in validateWaitingList
                    //RemoveNotification();// will release in validateWaitingList

                    OnCallError(errorThrown);
                }
            });

            checkedEvent.startDate = startDate;
            checkedEvent.startHour = startHour;
            checkedEvent.startMinutes = startMinutes;
            checkedEvent.endDate = endDate;
            checkedEvent.endHour = endHour;
            checkedEvent.endMinutes = endMinutes;
            checkedEvent.bookingRoom = bookingRoom;
            checkedEvent.isRecurred = isRecurred;
            checkedEvent.rFrequency = rFrequency;
            checkedEvent.rInterval = rInterval;
            checkedEvent.rOptions = rOptions;
        }
    }, 500);
}

function validateDatesWaitingList(listName) {

    var url = $().SPServices.SPGetCurrentSite() + '/_vti_bin/RBSService.svc/GetCalendarOverlapWaitingList';
    //AddNotification(); //added in validateBookEvents
    $.ajax({
        url: url,
        dataType: "json",
        type: "GET",
        cache: false,
        data: { "webUrl": $().SPServices.SPGetCurrentSite(),
            "listName": listName,
            "startDate": checkedEvent.startDate,
            "startHour": checkedEvent.startHour,
            "startMinutes": checkedEvent.startMinutes,
            "endDate": checkedEvent.endDate,
            "endHour": checkedEvent.endHour,
            "endMinutes": checkedEvent.endMinutes,
            "bookingRoom": checkedEvent.bookingRoom,
            "currentEventId": currentEventId,
            "isRecurred": checkedEvent.isRecurred,
            "rFrequency": checkedEvent.rFrequency,
            "rInterval": checkedEvent.rInterval,
            "rOptions": checkedEvent.rOptions,
            "isAdmin": hasFullControlPermission ? "1" : "0"
        },
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            g_eventOverlapped = false; //release temporary status while checking
            RemoveNotification();

            OnCallCompleteWaitingList(data.GetCalendarOverlapWaitingListResult.Message, data.GetCalendarOverlapWaitingListResult.OverlapCount);

//            if (data.GetCalendarOverlapResult.UsedResourceIDs) {
//                usedResourceIDs = data.GetCalendarOverlapWaitingListResult.UsedResourceIDs.split(",");
//            }
//            else {
//                usedResourceIDs = [];
//            }

//            BlockResourceRequest();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            g_eventOverlapped = false; //release temporary status while checking
            RemoveNotification();

            OnCallErrorWaitingList(errorThrown);
        }
    });
}

function OnCallComplete(result) {
    isCheckingDuplicateError = false;

    if (result != "") {

        if (result.substring(0, 94) == "Time Overlap Warning!<br/>Your selected time overlaps with the following booking(s):<br/><br/>") {
            $(".bookingstatus").show();
            $(".bookingstatus-label").html("Booking existed<br/>in Book Events");
            $(".bookingstatus-info").html(result.replace("Time Overlap Warning!<br/>Your selected time overlaps with the following booking(s):<br/><br/>", ""));

            //TODO: check in WaitingList for max 2 items
            validateDatesWaitingList("Waiting List");

        }
        else {
            $(".bookingstatus").hide();

            $(".waitstatus").show();
            $(".waitstatus-label").html("Error");
            $(".waitstatus-info").html(result);

            // this makes sure that we've covered this event
            eventType = "WaitingList"; // to get content in .waitstatus-info
            RemoveNotification();
            g_eventOverlapped = true;
        }

//        // this makes sure that we've covered this event
//        eventType = "WaitingList"; // to get content in .waitstatus-info
//        g_eventOverlapped = true;
    }
    else {
        $(".waitstatus").hide();
        $(".waitstatus-label").html("");
        $(".waitstatus-info").html("");

        $(".bookingstatus").show();
        $(".bookingstatus-label").html("Room is<br/> available");
        $(".bookingstatus-info").html("There is no booking for " + $("#" + g_strControlIDs["SPBookingRoom"]).find("option:selected").text() + " room at your selected time. You can book this room directly in Book Events.");

        // this makes sure that we've covered this event
        eventType = "BookEvents";
        RemoveNotification();
        g_eventOverlapped = true;
    }
}

function OnCallCompleteWaitingList(result, overlapCount) {
    isCheckingDuplicateError = false;

    if (result != "") {
        $(".waitstatus").show();

        $(".waitstatus-label").html("Error");
        $(".waitstatus-info").html(result);

        // this makes sure that we've covered this event
        eventType = "WaitingList";
        g_eventOverlapped = true;
    }
    else {
        $(".waitstatus").hide();

        $(".waitstatus-label").html("");
        $(".waitstatus-info").html("");

        // this makes sure that we've covered this event
        eventType = "BookEvents"; //reset to BookEvents
        g_eventOverlapped = false;
    }
}

function OnCallError(error) {
    if (error !== null) {
        isCheckingDuplicateError = true;
        RemoveNotification();
        g_eventOverlapped = true; //prevent Save action

        $(".waitstatus").show();
        $(".waitstatus-label").html("Error");
        $(".waitstatus-info").html("There's an error when checking events");
    }
}

function OnCallErrorWaitingList(error) {
    if (error !== null) {
        isCheckingDuplicateError = true;
        g_eventOverlapped = true; //prevent Save action

        $(".waitstatus").show();
        $(".waitstatus-label").html("Error");
        $(".waitstatus-info").html("There's an error when checking events");
    }
}

function BlockResourceRequest() {
    var $container = $("td:contains(Resource Request):last").next();
    $container.find("select[id$=SelectCandidate] option").removeAttr("disabled");
    if (usedResourceIDs.length > 0) {
        for (var i = 0; i < usedResourceIDs.length; i++) {
            $container.find("select[id$=SelectCandidate] option[value=" + usedResourceIDs[i] + "]").attr("disabled", "disabled");

            if ($container.find("select[id$=SelectResult] option[value=" + usedResourceIDs[i] + "]").length > 0) {
                $container.find("select[id$=SelectResult]").val(usedResourceIDs[i]).dblclick();
            }
        }
        $container.find("select[id$=SelectCandidate] option").removeAttr("selected");
    }
}

function ShowAvailableResources(roomId) {
    var currentWebUrl = $().SPServices.SPGetCurrentSite();

    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: "Meeting Rooms",
        CAMLViewFields: "<ViewFields><FieldRef Name='AvailableResources' /></ViewFields>",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>" + roomId + "</Value></Eq></Where></Query>",
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                var strLookup = $(this).attr("ows_AvailableResources");

                if (strLookup) {
                    $(".availableresources").show();
                    var $container = $(".availableresources-info");
                    $container.html(""); //reset content
                    var arrLookupItems = strLookup.split(";#");
                    for (var i = 0; i < arrLookupItems.length; i = i + 2) {
                        $container.append("<div><a href='" + currentWebUrl + "/Lists/Resources/DispForm.aspx?ID=" + arrLookupItems[i] + "' target='_blank'>" + arrLookupItems[i + 1] + "</a></div>");
                    }
                }
                else {
                    $(".availableresources").hide();
                    $(".availableresources-info").html("");
                }
            });
        }
    });
}

function ShowMeetingRoomInfo(roomId){
    var currentWebUrl = $().SPServices.SPGetCurrentSite();

    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: "Meeting Rooms",
        CAMLViewFields: "<ViewFields><FieldRef Name='RoomLocation' /><FieldRef Name='NumberOfSeats' /><FieldRef Name='Attachments' /></ViewFields>",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>" + roomId + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions><IncludeAttachmentUrls>True</IncludeAttachmentUrls></QueryOptions>",
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                var fullHTML = "<div style='width:50%;float:left;padding-top:5px;'>Floor: " + ($(this).attr("ows_RoomLocation")?$(this).attr("ows_RoomLocation"):'') + "</div>"
                             + "<div style='width:50%;float:left;padding-top:5px;'>Number of Seats: " + ($(this).attr("ows_NumberOfSeats")?parseInt($(this).attr("ows_NumberOfSeats")):'') + "</div>";

                if ($(this).attr("ows_Attachments") != 0) {
                    var attachmentsHTML = '',
                        attachmentsArray = $(this).attr("ows_Attachments").split(";#");

                    attachmentsHTML = "<ul style='list-style-type: none; margin:0;padding-left:10px;'>";
                    for (var i = 0; i < attachmentsArray.length; i++) {
                        if (attachmentsArray[i]) {
                            attachmentsHTML += "<li><img src='/_layouts/images/attach.gif' alt='Attachment'/> <a href='" + attachmentsArray[i] + "' target='_blank'>" + attachmentsArray[i].split("/")[attachmentsArray[i].split("/").length - 1] + "</a></li>"
                        }
                    }
                    attachmentsHTML += "</<ul>";

                    fullHTML += "<div style='float:left;padding-top:5px;'>Attachments:</div>"
                              + "<div style='float:left;padding-top:5px;'>" + attachmentsHTML + "</div>";
                }

                $("tr:has(>td.ms-formlabel:contains('Meeting Room'))").find(".ms-formbody a").after("<div>" + fullHTML + "</div>");
            });
        }
    });
}

//overide in groupeditempicker.js
function GipRemoveSelectedItems(master) { ULSEeZ: ; var handler = master.removeControl.getAttribute("onbeforeremove"); if (handler != null && handler != "") if (!eval(handler + "(master)")) return; var needToAdjustCandidateBox = false; if (master.resultControl.offsetWidth > master.candidateControl.offsetWidth) needToAdjustCandidateBox = true; for (var dirty = false, id = null, i = 0; i < master.resultControl.options.length; i++) if (master.resultControl.options[i].selected) { for (var found = false, n = 0; !master.alwaysAllowDelete && n < master.initialSelection.length; n++) if (master.resultControl.options[i].value == master.initialSelection[n][0]) found = true; if (!found) { dirty = true; id = master.resultControl.options[i].value; master.resultControl.options[i] = null; i-- } } if (dirty) { GipSetHiddenControlValue(master); GipRefreshGroupCore(master); master.removeControl.disabled = true; for (var i = 0; i < master.candidateControl.options.length; i++) if (master.candidateControl.options[i].value == id) { master.candidateControl.selectedIndex = i; GipSelectCandidateItems(master); break } } var handler = master.removeControl.getAttribute("onafterremove"); if (handler != null && handler != "") eval(handler + "(master)"); BlockResourceRequest() }

//onload
$(function () {

    if ($("input[title='Subject']").length > 0) {
        //Events for NewForm and EditForm

        //prevent editing of a single instance of Recurring event
        var formUrl = new Url(window.location.href);
        if (formUrl.query.ID && formUrl.query.ID.split(".").length > 1) {
            if (formUrl.query.ID.split(".")[1] == 1) {
                formUrl.query.ID = formUrl.query.ID.split(".")[2];
                window.location.href = formUrl;
            }
            else {
                formUrl.query.ID = formUrl.query.ID.split(".")[0];
                window.location.href = formUrl;
            }
        }


        /* BEGIN: Block Multi lookup */
        var selectedValues = "",
                    query = "";

        //hide Resource Request in Waiting List
        $("td:contains(Resource Request):last").parent().hide().after("<tr><td width='190px' valign='top' nowrap='true' class='ms-formlabel'><h3 class='ms-standardheader'><nobr>Resources</nobr></h3></td><td valign='top' class='ms-formbody'>Not available in Waiting List</td></tr>");

        $("td:contains(Resource Request):last").next().find("select[id$=SelectResult] option").each(function () {
            selectedValues += "<Value Type='Number'>" + $(this).val() + "</Value>";
        });

        if (selectedValues) {
            query = "<And><Or><Eq><FieldRef Name='IsPrivate' /><Value Type='Boolean'>0</Value></Eq><In><FieldRef Name='ID'/><Values>" + selectedValues + "</Values></In></Or><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq></And>";
        }
        else {
            query = "<And><Eq><FieldRef Name='IsPrivate' /><Value Type='Boolean'>0</Value></Eq><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq></And>"
        }

        $().SPServices.SPFilterDropdown({
            relationshipWebURL: $().SPServices.SPGetCurrentSite(),
            relationshipList: "Resources",
            relationshipListColumn: "Title",
            columnName: "Resource Request",
            CAMLQuery: query
        });

        $().SPServices.SPSetMultiSelectSizes({
            multiSelectColumn: "Resource Request",
            minWidth: 139
        });

        $("td:contains(Resource Request):last").next().find("button").width(60);
        /* END: Block Multi lookup */

        /* BEGIN: Complex to Simple Dropdown */
        var queryMeetingRooms = "<Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq>";

        $().SPServices.SPFilterDropdown({
            relationshipWebURL: $().SPServices.SPGetCurrentSite(),
            relationshipList: "Meeting Rooms",
            relationshipListColumn: "Title",
            columnName: "Meeting Room",
            CAMLQuery: queryMeetingRooms
        });


        $().SPServices.SPComplexToSimpleDropdown({
            columnName: "Meeting Room",
            completefunc: function () {
                isMeetingRoomComplex = true;
                $("#SPComplexToSimpleDropdown_MeetingRoom").change(function () {
                    ShowAvailableResources($(this).find("option:selected").val());
                });
                $("#SPComplexToSimpleDropdown_MeetingRoom").change();
            }
        });
        /* END: Complex to Simple Dropdown */

        /* BEGIN: set current user */

        var fieldUser = $().SPFindPeoplePicker({
            peoplePickerDisplayName: "User",
            checkNames: false
        });

        if (fieldUser.dictionaryEntries.length == 0) {
            var thisUser = $().SPServices.SPGetCurrentUser({
                fieldNames: ["Name", "EMail", "Department", "WorkPhone"]
            });

            $().SPFindPeoplePicker({
                peoplePickerDisplayName: "User",
                valueToSet: thisUser.Name,
                checkNames: true
            });

            lastUserName = thisUser.Name;
            $("input[title=Email]").val(thisUser.EMail);
        }
        else {
            var fieldNewUser = $().SPFindPeoplePicker({
                peoplePickerDisplayName: "User",
                checkNames: false
            });

            if (fieldNewUser.dictionaryEntries.length > 0) {
                lastUserName = fieldNewUser.dictionaryEntries[0].AccountName;
            }
        }

        $("input[title=Email]").attr("readonly", "readonly").addClass("disabled-text"); //disable Email

        if (!hasFullControlPermission) {
            //disabled User - People Picker
            setTimeout(function () {
                var $UserContainer = $("td.ms-formlabel:contains(User):last").next();
                $UserContainer.find("*[contentEditable]").attr("contentEditable", "false").addClass("disabled-text");
                $UserContainer.find("span[id$='_UserField'] img").hide();
            }, 500);
        }
        else {
            var intervalUserChange = setInterval(function () {
                var fieldNewUser = $().SPFindPeoplePicker({
                    peoplePickerDisplayName: "User",
                    checkNames: false
                });

                if (fieldNewUser.dictionaryEntries.length > 0 && fieldNewUser.dictionaryEntries[0].AccountName != lastUserName) {
                    lastUserName = fieldNewUser.dictionaryEntries[0].AccountName;
                    $("input[title=Email]").val(fieldNewUser.dictionaryEntries[0].Email);
                }
            }, 1000);


        }

        /* END: set current user */

        /* BEGIN: prevent double booking */
        // SP.PageContextInfo.get_currentLanguage() = 1033

        $("tr:has(>td.ms-formlabel:contains('End Time'))").after("<tr class='bookingstatus' style='display:none'><td class='ms-formlabel bookingstatus-label' style='color:green;' valign='top' nowrap='true'>Booking status</td><td class='ms-formbody bookingstatus-info' style='color:green;' valign='top'></td></tr><tr class='waitstatus' style='display:none'><td class='ms-formlabel waitstatus-label' style='color:red;' valign='top' nowrap='true'>Status</td><td class='ms-formbody waitstatus-info' style='color:red;' valign='top'></td></tr>");
        $("tr:has(>td.ms-formlabel:contains('Resource Request'))").before("<tr class='availableresources' style='display:none'><td class='ms-formlabel availableresources-label' valign='top' nowrap='true'><h3 class='ms-standardheader'><nobr>Available Resources</nobr></h3></td><td class='ms-formbody availableresources-info' valign='top'></td></tr>");

        g_strControlIDs["SPEventDate"] = $("input[title='Start Time']").attr("id");
        g_strControlIDs["SPEndDate"] = $("input[title='End Time']").attr("id");


        /* BEGIN: set Minutes 0, 15, 30, 45 only */
        $("#" + g_strControlIDs["SPEventDate"] + "Minutes").find("option[value!=00][value!=15][value!=30][value!=45]").remove()
        $("#" + g_strControlIDs["SPEndDate"] + "Minutes").find("option[value!=00][value!=15][value!=30][value!=45]").remove();

        if ($("input[id$=RecurrenceField]").prop("checked") == true) {
            var $StartTimeContainer = $("td.ms-formlabel:contains('Start Time')").next();
            $StartTimeContainer.find("select[id$=DateTimeFieldDateMinutes] option[value!=00][value!=15][value!=30][value!=45]").remove();

            var $EndTimeContainer = $("td.ms-formlabel:contains('End Time')").next();
            $EndTimeContainer.find("select[id$=DateTimeFieldDateMinutes] option[value!=00][value!=15][value!=30][value!=45]").remove();
        }
        /* END: set Minutes 0, 15, 30, 45 only */


        if (!isMeetingRoomComplex) {
            g_strControlIDs["SPBookingRoom"] = $("select[title='Meeting Room']").attr("id");

            /* BEGIN: room changed - reload available resources*/
            $("select[title='Meeting Room']").change(function () {
                ShowAvailableResources($(this).find("option:selected").val());
            });
            $("select[title='Meeting Room']").change();
            /* END: room changed - reload available resources*/
        }
        else {
            g_strControlIDs["SPBookingRoom"] = "SPComplexToSimpleDropdown_MeetingRoom";
        }


        FindOverlappedEvents("Book Events");

        /* END: prevent double booking */

        //change Title to Subject
        //var $objTitle = $("td.ms-formlabel:contains(Title):last");
        //$objTitle.html($objTitle.html().replace(/Title/g, "Subject"));

        $("td.ms-formlabel:contains('Subject'):last .ms-standardheader").css("font-weight", "bold");


        FillValuesFromBookEvents(); // MoveToWaitingList
    }
    else {
        //Events for DispForm

        //prevent editing of a single instance of Recurring event
        var formUrl = new Url(window.location.href);
        if (formUrl.query.ID && formUrl.query.ID.split(".").length > 1) {
            $("a[id*=EditItem]").hide();
            setInterval(function () {
                $("a[id*=EditItem]").hide();
            }, 500);
        }

        //Resize multi lookup field
        var disFormLookupMultiHTML = $("#SPFieldLookupMulti").html();
        if (disFormLookupMultiHTML) {
            var disFormLookupMultiHTMLNew = disFormLookupMultiHTML.replace(/<\/A>;/gi, "</A><BR/>");
            $("#SPFieldLookupMulti").html(disFormLookupMultiHTMLNew);
        }

        //Hide Recurrence
        //$("tr:has(>td.ms-formlabel:contains('Recurrence'))").hide();
        if ($.trim($("#SPFieldRecurrence").text()) == "") {
            $("#SPFieldRecurrence").parent().hide();
        }

        //Available resources
        $("tr:has(>td.ms-formlabel:contains('Resource Request'))").before("<tr class='availableresources' style='display:none'><td valign='top' nowrap='true' class='ms-formlabel availableresource-label'><h3 class='ms-standardheader'>Available Resources</h3></td><td valign='top' class='ms-formbody availableresources-info'></td></tr>");
        var roomId = new Url($("tr:has(>td.ms-formlabel:contains('Meeting Room'))").find(".ms-formbody a").attr("href")).query.ID;
        ShowAvailableResources(roomId);
        ShowMeetingRoomInfo(roomId);

        $("tr:has(>td.ms-formlabel:contains('User'))").before("<tr><td valign='top' nowrap='true' class='ms-formlabel' style='border-top:none'>Booked By:</td><td valign='top' class='ms-formbody' style='background:none;border-top:none'></td></tr>");
        $("tr:has(>td.ms-formlabel:contains('Subject'))").before("<tr><td valign='top' nowrap='true' class='ms-formlabel' style='padding-top:20px;'>Event:</td><td valign='top' class='ms-formbody' style='background:none'></td></tr>");
        $("td.ms-formlabel:contains('Subject'):last").next().css("font-weight", "bold"); //bold Title/Subject

        //format date
        $(".ms-formbody[id=SPFieldDateTime]").each(function () {
            var $this = $(this),
                strDate = moment($this.text()).format("dddd, MMMM DD YYYY, hh:mm A");
            $this.text(strDate);
        });
    }

});

function FillValuesFromBookEvents() {
    if ($.cookie('HasValuesMoveToWaitingList') == 1) {
        $("input[title='Department']").val($.cookie('Department'));
        //$("input[title='Email']").val($.cookie('Email'));
        $("input[title='Phone Number']").val($.cookie('CellPhone'));
        $("input[title='Subject']").val($.cookie('Subject'));
        $("#" + g_strControlIDs["SPBookingRoom"]).val($.cookie('MeetingRoom'));


        $("#" + g_strControlIDs["SPEventDate"]).val($.cookie('StartDate'));
        $("#" + g_strControlIDs["SPEventDate"] + "Hours").val($.cookie('StartHour'));
        $("#" + g_strControlIDs["SPEventDate"] + "Minutes").val($.cookie('StartMinute'));
        $("#" + g_strControlIDs["SPEndDate"]).val($.cookie('EndDate'));
        $("#" + g_strControlIDs["SPEndDate"] + "Hours").val($.cookie('EndHour'));
        $("#" + g_strControlIDs["SPEndDate"] + "Minutes").val($.cookie('EndMinute'));

        //remove cookie
        $.removeCookie('HasValuesMoveToWaitingList', { path: '/' });
        $.removeCookie('Department', { path: '/' });
        $.removeCookie('Email', { path: '/' });
        $.removeCookie('CellPhone', { path: '/' });
        $.removeCookie('Subject', { path: '/' });
        $.removeCookie('MeetingRoom', { path: '/' });
        $.removeCookie('StartDate', { path: '/' });
        $.removeCookie('StartHour', { path: '/' });
        $.removeCookie('StartMinute', { path: '/' });
        $.removeCookie('EndDate', { path: '/' });
        $.removeCookie('EndHour', { path: '/' });
        $.removeCookie('EndMinute', { path: '/' });
    }


}
